<template>
  <div>
    <el-row>
      <el-col :span="7">
        <chessboard :onPromotion="promote" :orientation="boardColor" @onMove="getLearnBoardInfo"
                    :fen="gameFen" :style="{opacity: isBoss ? 0.05 : 1 }" />
      </el-col>
      <el-col :span="17">
        <el-table :data="moveHistory" border stripe
                  highlight-current-row :height="280"
                  @cell-click="handleSelectMove">
          <el-table-column
              type="index"
              width="50"
              label="步数">
          </el-table-column>
          <el-table-column
              prop="white"
              label="白方"
              width="80"
          >
          </el-table-column>
          <el-table-column
              prop="whiteCurrentValue"
              label="评分"
              width="80"
          >
            <template slot-scope="{ row }">
              <span :class="fontLightClass(row.whiteType)">{{row.whiteCurrentValue}}</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="whiteValueDiff"
              label="分差"
              width="80"
          >
          </el-table-column>
          <el-table-column
              prop="whiteBest"
              label="最优"
              width="80"
          >
          </el-table-column>
          <el-table-column
              prop="whiteType"
              label="类型"
              width="105"
          >
            <template slot-scope="{ row }">
              <span :class="fontLightClass(row.whiteType)">{{row.whiteType}}</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="black"
              label="黑方"
              width="80"
          >
          </el-table-column>
          <el-table-column
              prop="blackCurrentValue"
              label="评分"
              width="80"
          >
          </el-table-column>
          <el-table-column
              prop="blackValueDiff"
              label="分差"
              width="80"
          >
            <template slot-scope="{ row }">
              <span :class="fontLightClass(row.blackType)">{{row.blackValueDiff}}</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="blackBest"
              label="最优"
              width="80"
          >
          </el-table-column>
          <el-table-column
              prop="blackType"
              label="类型"
              width="105"
          >
            <template slot-scope="{ row }">
              <span :class="fontLightClass(row.blackType)">{{row.blackType}}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <div  :style="{opacity: isBoss ? 0.5 : 1 }" >
            <el-tooltip class="item" effect="dark" content="翻转黑白朝向" placement="top">
              <el-button  type="info" icon="el-icon-refresh" style="margin:4px" size="small" @click="reverseBoard"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="回到最开始" placement="top">
              <el-button type="primary"  round icon="el-icon-d-arrow-left" style="margin:4px"  size="small" @click="jumpToBegin" :loading=autoLoading ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="后退一步" placement="top">
              <el-button  type="primary" round icon="el-icon-arrow-left" style="margin:4px"  size="small"  @click="jumpToBack" :loading=autoLoading></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="前进一步" placement="top">
              <el-button  type="primary" round icon="el-icon-arrow-right" style="margin:4px" size="small" @click="jumpToNext" :loading=autoLoading></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="跳转到末尾" placement="top">
              <el-button   type="primary" round icon="el-icon-d-arrow-right" style="margin:4px"  size="small" @click="jumpToEnd" :loading=autoLoading></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="自动播放" placement="top">
              <el-button type="warning" round icon="el-icon-caret-right" style="margin:4px"  size="small" :loading=autoLoading @click="autoMove"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="老板键" placement="top">
              <el-button type="danger" round icon="el-icon-s-platform" style="margin:4px"  size="small" :loading=autoLoading @click="isBoss=!isBoss"></el-button>
            </el-tooltip>

            <el-tooltip class="item" effect="dark" content="返回" placement="top">
              <el-button  type="danger" round style="margin:4px" size="small" icon="el-icon-circle-close" :loading="autoLoading || analyzeLoading" @click="back2GameList"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分析" placement="top" >
              <el-button class="firstLine" type="success" round style="margin:4px;float: right" size="small" icon="el-icon-s-data" :loading=analyzeLoading @click="analyze">
                {{analyzeLoading ? analyzeProgress + "%" : ''}} 分析

              </el-button>
            </el-tooltip>
          </div>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="7">
        <div class="f-m-l-5" >
          <el-descriptions title="对局信息" :column="2" size="medium">
            <el-descriptions-item label="白方">{{ gameInfo.white }}</el-descriptions-item>
            <el-descriptions-item label="白方ELO">{{ gameInfo.whiteElo }}</el-descriptions-item>
            <el-descriptions-item label="黑方">{{ gameInfo.black }}</el-descriptions-item>
            <el-descriptions-item label="黑方ELO">{{ gameInfo.blackElo }}</el-descriptions-item>
          </el-descriptions>
          <el-descriptions :column="1" size="medium">
            <el-descriptions-item label="结果">{{ gameInfo.result }}</el-descriptions-item>
            <el-descriptions-item label="开局">{{ gameInfo.opening }}</el-descriptions-item>
            <el-descriptions-item label="赛事">{{ gameInfo.event }}</el-descriptions-item>
            <el-descriptions-item label="类型">{{ gameInfo.type }}</el-descriptions-item>
            <el-descriptions-item label="限时">{{ gameInfo.time }}</el-descriptions-item>
            <el-descriptions-item label="对局时间">{{ gameInfo.gameDate }}</el-descriptions-item>
            <el-descriptions-item label="链接">{{ lichessGameUrl + gameInfo.hash }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-col>
      <el-col :span="17">
        <el-table :data="blunders" border stripe
                  highlight-current-row :height="320"
                  disabled>
          <el-table-column
              type="index"
              label="序号"
              width="50">
          </el-table-column>
          <el-table-column  :show-overflow-tooltip="true"
              prop="fen"
              label="fen"
              width="120"
          >
          </el-table-column>
          <el-table-column
              prop="badMove"
              label="错着"
              width="100"
          >
          </el-table-column>
          <el-table-column
              prop="correctMove"
              label="正着"
              width="100"
          >
          </el-table-column>
          <el-table-column
              prop="value"
              label="分差"
              width="100"
          >
          </el-table-column>
          <el-table-column
              prop="learn"
              label="已学习"
              width="80"
          >
          </el-table-column>
          <el-table-column
              prop="disabled"
              label="禁用状态"
              width="80"
          >
          </el-table-column>
          <el-table-column
              prop="type"
              label="类型"
              width="100"
          >
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
          >
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="selectExercise(scope.row)">选择</el-button>
              <el-button type="danger" size="mini" @click="disableExercise(scope.row)">禁用</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import emitvue from "@/lib/emitvue";
import * as utils from "@/lib/utils";
import {existValue, hex2str, invoke, parseFenDropHistory} from "@/lib/utils";
import {chessboard} from 'vue-chessboard'
import chessmate from "@/lib/chessmate";
import Chessmate from "@/lib/chessmate";
import {lichessGameUrl} from "@/lib/constants";
import _ from "lodash";
import Database from "@/lib/database";
import moment from "moment";


export default {
  name: "UserBoard",
  data() {
    return {
      boardColor: 'white',
      gameFen: utils.newGame,
      moveHistory: [],
      autoLoading: false,
      rawData: [],
      isBoss: false,
      isDev: false,
      blunders: [],
      moveNum: -1,
      // 操作棋盘用
      moveList: [],
      analyzeLoading: false,
      tempGameFen: utils.newGame,
      lichessGameUrl: lichessGameUrl,
      analyzeProgress: 0,
      fastAnalyze: false,
    }
  },
  methods: {
    // 升变
    promote() {
      if (confirm("是否升变为后？")) {
        return 'q'
      } else {
        if (confirm("是否升变为车？")) {
          return 'r'
        } else {
          if (confirm("是否升变为马？")) {
            return 'n'
          } else {
            if (confirm("是否升变为象？")) {
              return 'b'
            }
          }
        }
      }
      return 'q'
    },
    async getLearnBoardInfo(data) {
      console.log("data", data)
      this.gameFen = parseFenDropHistory(data.fen)
      if (data.history?.length) {
        this.$notify({duration: 1000, title: '通知', message: "开局名称不允许特殊字符", type: 'warning'})
        // TODO 直接赋值上一步的tempFen不起作用 只能这样
        this.moveNum--
        this.moveNum++
        this.moveNum++
        return
      }
      this.tempGameFen = this.gameFen
    },
    // 选择某一列跳转
    handleSelectMove(row, column, cell, event) {
      const index = row.index
      const property = column.property
      let isWhite = false
      if (property.indexOf('white') !==-1) {
        isWhite = true
      }
      this.moveNum = (index - 1) * 2 + (isWhite ? 0 : 1)
    },
    // 几个跳转的按钮
    jumpToBegin() {
      if (!this.isEnterChild) {
        this.moveNum = -1
        this.gameFen = utils.newGame
      }
    },
    jumpToBack() {
      this.moveNum--
      if (this.moveNum < 0 ) {
        this.$notify({duration: 1000, title: '通知', message: `已经来到了棋局开始`, type: 'warning'})
        this.jumpToBegin()
      }

    },
    jumpToNext() {
      if (this.moveNum + 1 >= this.moveList.length) {
        // 没必要做任何操作
        this.$notify({duration: 1000, title: '通知', message: `已经来到了棋局末尾`, type: 'warning'})
        return
      }
      this.moveNum ++
    },
    jumpToEnd() {
      this.moveNum = this.moveList.length - 1

    },
    reverseBoard() {
      this.boardColor = this.boardColor === 'white' ? 'black' : 'white';
    },
    // 自动播放
    async autoMove() {
      this.autoLoading = true
      this.jumpToBegin()
      for (let i=1;i<this.moveList.length;i++) {
        await utils.sleep(500)
        this.jumpToNext()
      }
      this.autoLoading = false
    },
    // 返回到列表
    back2GameList() {
      emitvue.$emit('exitUserGame')
    },
    // 将走法解析成历史记录
    parseMove2History(data) {
      this.moveHistory = [];
      this.moveList = []
      const temp = []
      let black = [];
      let white = [];
      let tempFen = utils.newGame
      // 先把黑白分开
      for (let i = 0; i < data.length; i++) {
        tempFen = chessmate.move(tempFen, data[i].move)
        this.moveList.push({
          move: data[i].move,
          fen: tempFen,
          currentValue: data[i]?.currentValue,
          valueDiff: data[i]?.valueDiff,
          type: data[i]?.type,
          bestmove: data[i]?.bestmove,
        })
        if (i % 2 === 0) {
          white.push({
            move: data[i].move,
            currentValue: data[i]?.currentValue,
            valueDiff: data[i]?.valueDiff,
            type: data[i]?.type,
            bestmove: data[i]?.bestmove,
          });
        } else {
          black.push({
            move: data[i].move,
            currentValue: data[i]?.currentValue,
            valueDiff: data[i]?.valueDiff,
            type: data[i]?.type,
            bestmove: data[i]?.bestmove,
          })
        }

      }
      for (let i = 0; i < white.length; i++) {
        let list = {
          index: i + 1,
          white: white[i].move,
          whiteValueDiff: existValue(white[i].valueDiff) ? white[i].valueDiff : '',
          whiteCurrentValue: existValue(white[i].currentValue) ? white[i].currentValue : '',
          whiteBest: existValue(white[i].bestmove) ? white[i].bestmove : '',
          whiteType: existValue(white[i].type) ? white[i].type : '',
          // 白棋肯定会有 黑棋有可能还没开始下
          black: black[i]?.move || '',
          blackValueDiff: existValue(black[i]?.valueDiff) ? black[i]?.valueDiff : '',
          blackCurrentValue: existValue(black[i]?.currentValue) ? black[i]?.currentValue : '',
          blackBest: existValue(black[i]?.bestmove) ? black[i]?.bestmove : '',
          blackType: existValue(black[i]?.type) ? black[i]?.type : '',
        }
        temp.push(list);
      }
      this.moveHistory = _.cloneDeep(temp)
    },
    async analyze() {
      this.analyzeLoading = true
      this.analyzeProgress = 0
      console.log("this.gameData", this.rawData)
      const res = await Chessmate.analyzeGame(this.rawData, utils.newGame, this.fastAnalyze)
      this.rawData = res
      // 重新转日期
      const gameInfo = this.gameInfo
      gameInfo.gameDate = moment(gameInfo.gameDate, 'YYYY-MM-DD HH:mm:ss').valueOf()
      await Chessmate.getExercise(gameInfo, res)
      // 获取错题
      await Database.saveAnalyzeResult(this.gameInfo, res)
      this.parseMove2History(res)
      this.analyzeLoading = false
      this.$notify({duration: 1000, title: '通知', message: `分析完成`, type: 'success'})
      console.log("this.rawData", this.rawData)
      await Database.saveAnalyzeResult(this.gameInfo, this.rawData)
      await this.getExercise()
    },
    selectExercise(data) {
      this.moveNum = data.moveNum
    },
    async disableExercise(data) {
      console.log("data", data)
      await Database.disableExercise(data.fenHash, data.moveNum)
      this.$notify({duration: 1000, title: '通知', message: `处理成功`, type: 'success'})
      await this.getExercise()
    },
    // 获取错题
    async getExercise() {
      const blunders = await Database.getExercise(this.gameInfo.hash)
      for (const item of blunders) {
        item.fen = hex2str(item.fenHash)
        item.disabled = item.disabled == 0 ? '否' : '是'
        item.learn = item.learn == 0 ? '否' : '是'
      }
      this.blunders = _.cloneDeep(blunders)
    },
    fontLightClass(type) {
      console.log("data", type)
      if (type === '普通') return 'normal'
      if (type === '错着') return 'mistake'
      if (type === '败着') return 'blunder'
      if (type === '不精确') return 'incorrect'
      if (type === '最佳') return 'best'
    },
    async getSetting() {
      this.appPath = await invoke('getCurrentPath', null)
      let config = await invoke('get', {name: 'setting', type: 'database'})
      this.fastAnalyze = config.rapidAnalyzeGame || false
    },
  },
  props: {
    gameInfo: {
    },
  },
  watch: {
    // 监控棋局步骤
    moveNum(moveNum) {
      if (!this.moveList[moveNum]) {
        if (moveNum === 0 ||moveNum < 0) {
          return this.jumpToBegin()
        } else {
          return this.jumpToEnd()
        }
      } // 棋局末尾 或者开始
      this.gameFen = this.moveList[moveNum].fen
    },
  },
  async mounted() {
    await this.getSetting()
    this.rawData = utils.safeJsonParse(utils.hex2str(this.gameInfo.data))
    this.parseMove2History(this.rawData)
    this.isDev = location.protocol.indexOf('http') !== -1;
    await this.getExercise()
    // 如果是开发模式，默认走老板键
    const isHome = await invoke('isHome', null)
    if (isHome === 'true' || isHome === true) {

    } else {
      this.isBoss = this.isDev
    }
    // 每次收到消息就解析
    emitvue.$on('parseResult', (data)=> {
      const index = data.index
      this.analyzeProgress =  String((index / this.rawData.length)  * 100).slice(0, 4)

    })
    // 解析结束的事件
    emitvue.$on('parseEnd', (data)=> {
      this.$notify({duration: 1000, title: '通知', message: `局面分析已全部完成`, type: 'success'})

    })
    emitvue.$once('clearUserGame', ()=>{
      this.moveList = []
      this.moveHistory = []
      this.moveNum = -1
    })
  },
  components: {
    chessboard
  },
}
</script>


<style scoped>
.blunder {
  color: red
}

.mistake {
  color: orange;
}

.incorrect{
  color: cornflowerblue;
}

.best {
  color: green;
}

.normal {
  color: black;
}
</style>